import { request } from '../utils/request'

export default {
  namespaced: true,
  state: {
    userInfo: null,
    token: uni.getStorageSync('token') || '',
    isLogin: false,
    isInfoComplete: false
  },
  
  getters: {
    // 获取用户ID
    userId: state => state.userInfo?.id || '',
    // 获取用户昵称
    nickname: state => state.userInfo?.nickname || '',
    // 获取用户头像
    avatar: state => state.userInfo?.avatar || '',
    // 获取用户手机号
    phone: state => state.userInfo?.phone || ''
  },
  
  mutations: {
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    SET_TOKEN(state, token) {
      state.token = token
    },
    SET_IS_LOGIN(state, isLogin) {
      state.isLogin = isLogin
    },
    SET_IS_INFO_COMPLETE(state, isInfoComplete) {
      state.isInfoComplete = isInfoComplete
    },
    CLEAR_USER_INFO(state) {
      state.userInfo = null
      state.token = ''
      state.isLogin = false
      state.isInfoComplete = false
    }
  },
  
  actions: {
    // 静默登录
    async silentLogin({ commit, state }) {
      try {
        // 检查本地是否有token
        if (state.token) {
          // 验证token是否有效
          const res = await this.dispatch('validateToken')
          if (res.success) {
            commit('SET_IS_LOGIN', true)
            commit('SET_USER_INFO', res.data.userInfo)
            commit('SET_IS_INFO_COMPLETE', res.data.isInfoComplete)
            return res.data
          } else {
            // token无效，清除token并重新静默登录
            this.dispatch('clearUserInfo')
          }
        }
        
        // 调用微信的静默登录接口
        const { code } = await uni.login()
        
        // 发送code到后端换取token
        const loginRes = await request('/api/login/silent', {
          method: 'POST',
          data: {
            code
          }
        })
        
        if (loginRes.success) {
          commit('SET_TOKEN', loginRes.data.token)
          commit('SET_USER_INFO', loginRes.data.userInfo)
          commit('SET_IS_LOGIN', true)
          commit('SET_IS_INFO_COMPLETE', loginRes.data.isInfoComplete)
          
          // 保存token到本地
          uni.setStorageSync('token', loginRes.data.token)
          
          return loginRes.data
        } else {
          throw new Error(loginRes.msg || '静默登录失败')
        }
      } catch (error) {
        console.error('静默登录失败:', error)
        throw error
      }
    },
    
    // 手机授权登录
    async phoneLogin({ commit }) {
      try {
        // 调用微信获取手机号接口
        const { errMsg, code, iv, encryptedData } = await uni.getUserProfile({
          desc: '用于完善会员资料'
        })
        
        if (errMsg !== 'getUserProfile:ok') {
          throw new Error('用户取消授权')
        }
        
        // 发送授权信息到后端
        const res = await request('/api/login/phone', {
          method: 'POST',
          data: {
            code,
            iv,
            encryptedData
          }
        })
        
        if (res.success) {
          commit('SET_TOKEN', res.data.token)
          commit('SET_USER_INFO', res.data.userInfo)
          commit('SET_IS_LOGIN', true)
          commit('SET_IS_INFO_COMPLETE', res.data.isInfoComplete)
          
          // 保存token到本地
          uni.setStorageSync('token', res.data.token)
          
          return res.data
        } else {
          throw new Error(res.msg || '手机授权登录失败')
        }
      } catch (error) {
        console.error('手机授权登录失败:', error)
        throw error
      }
    },
    
    // 完善用户信息
    async completeUserInfo({ commit }, userInfo) {
      try {
        const res = await request('/api/user/update', {
          method: 'POST',
          data: userInfo
        })
        
        if (res.success) {
          commit('SET_USER_INFO', res.data.userInfo)
          commit('SET_IS_INFO_COMPLETE', true)
          return res.data
        } else {
          throw new Error(res.msg || '完善信息失败')
        }
      } catch (error) {
        console.error('完善信息失败:', error)
        throw error
      }
    },
    
    // 验证token
    async validateToken({ state }) {
      try {
        const res = await request('/api/login/validate', {
          method: 'GET',
          header: {
            'Authorization': `Bearer ${state.token}`
          }
        })
        return res
      } catch (error) {
        console.error('验证token失败:', error)
        return { success: false }
      }
    },
    
    // 退出登录
    logout({ dispatch }) {
      dispatch('clearUserInfo')
      uni.reLaunch({
        url: '/pages/login/login'
      })
    },
    
    // 清除用户信息
    clearUserInfo({ commit }) {
      commit('CLEAR_USER_INFO')
      uni.removeStorageSync('token')
    }
  }
}